package com.lvyq.service.impl;

import com.lvyq.common.CurrencyEnum;
import com.lvyq.common.GoodsTypeConstant;
import com.lvyq.common.ShopTypeConstant;
import com.lvyq.model.bag.MyBag;
import com.lvyq.model.pasture.MyPasture;
import com.lvyq.model.pasture.PastureGoodsInfo;
import com.lvyq.model.receive.ReceiveMsg;
import com.lvyq.model.shop.ShopGoods;
import com.lvyq.model.user.User;
import com.lvyq.repository.MyBagRepository;
import com.lvyq.repository.ShopGoodsRepository;
import com.lvyq.repository.UserRepository;
import com.lvyq.repository.pasture.MyPastureRepository;
import com.lvyq.repository.pasture.PastureGoodsInfoRepository;
import com.lvyq.service.ShopService;
import com.lvyq.util.DateUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: weg
 * @description: 金币商城
 * @author: lvyq
 * @create: 2023-03-28 20:07
 **/
@Service
public class ShopServiceImpl implements ShopService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private ShopGoodsRepository shopGoodsRepository;


    @Resource
    private PastureGoodsInfoRepository pastureGoodsInfoRepository;

    @Resource
    private MyPastureRepository myPastureRepository;


    @Resource
    private UserRepository userRepository;

    @Resource
    private MyBagRepository myBagRepository;

    @Override
    public String orderReply(String replyContent, ReceiveMsg receiveMsg) {
        if (receiveMsg.getContent().equals("金币商城")){
            replyContent=JBShopReply(replyContent,receiveMsg);
        }
        //详情
        if (receiveMsg.getContent().startsWith("查看#")){
            replyContent=lookInfo( replyContent, receiveMsg);
        }
        //购买 购买#麦子种子*1
        if (receiveMsg.getContent().startsWith("购买#") || receiveMsg.getContent().startsWith("购买$")){
            replyContent =buyGoods(replyContent, receiveMsg);
        }


        //出售
        if (receiveMsg.getContent().startsWith("出售#")){
            replyContent=csGoods( replyContent, receiveMsg);
        }

        return replyContent;
    }

    /** 
    * @Description: 物品出售  出售#小麦种子*1
     * @param replyContent
 * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/19 20:36
    */
    
    private String csGoods(String replyContent, ReceiveMsg receiveMsg) {
        //获取物品名及数量
        String content = receiveMsg.getContent();
        String goodsName = content.split("#")[1].split("\\*")[0];
        Integer goodsNum = Integer.valueOf(content.split("#")[1].split("\\*")[1]);
        //判断背包中是否存在
        MyBag myBag=myBagRepository.findByGoodsNameAndOpenId(goodsName,receiveMsg.getFromUserName());
        if (myBag==null){
            replyContent="出售失败,背包中不存在物品【"+goodsName+"】";
            return replyContent;
        }
        //判断背包中数量是否充足
        if (myBag.getNum()<goodsNum){
            replyContent="出售失败,物品【"+goodsName+"】数量不足";
            return replyContent;
        }
        //获取物品属性  币种，回收价格
        ShopGoods goods = shopGoodsRepository.findByGoodsName(goodsName);
        Integer currency=goods.getCurrency();
        Integer sellingPrice=goods.getSellingPrice();
        Integer totalPrice = 0;
        User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
        if (currency==CurrencyEnum.JB.getType()){
                //金币
            totalPrice=sellingPrice*goodsNum;
            user.setJinbi(user.getJinbi()+totalPrice);
            replyContent=replyContent.replace("{num}",goodsNum.toString()).replace("{goodsName}",
                    goodsName).replace("{jinbi}",totalPrice+CurrencyEnum.JB.getEmoji()+"金币");

        }else {
            //TODO 钻石
            totalPrice=sellingPrice*goodsNum;
            replyContent=replyContent.replace("{num}",goodsNum.toString()).replace("{goodsName}",
                    goodsName).replace("{jinbi}",totalPrice+CurrencyEnum.ZS.getEmoji()+"钻石");

        }
        //修改用户余额
        mongoTemplate.save(user);
        //修改背包数量
        myBag.setNum(myBag.getNum()-goodsNum);
        if (myBag.getNum()==0){
            //删除数据
            Query query=  new Query().addCriteria(Criteria.where("goodsName").is(goodsName)).addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()));
            mongoTemplate.remove(query,MyBag.class);

        }else {
            myBagRepository.save(myBag);
        }
        //返回消息
        return replyContent;
    }


    /**
    * @Description: 购买物品
     * @param replyContent
   * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/18 20:33
    */

    private String buyGoods(String replyContent, ReceiveMsg receiveMsg) {
        String content = receiveMsg.getContent();
        //麦子种子*1
        String goodsName = "";
        String goodsNum = "";
        if (receiveMsg.getContent().startsWith("购买$")){
            goodsName= content.split("\\$")[1].split("\\*")[0];
            goodsNum= content.split("\\$")[1].split("\\*")[1];
        }else {
            goodsName= content.split("#")[1].split("\\*")[0];
            goodsNum= content.split("#")[1].split("\\*")[1];
        }
        ShopGoods goods =shopGoodsRepository.findByGoodsName(goodsName);
        if (goods!=null){
            //TODO 通过当前物品类型，判断当前物品是否可被购买--牧场商品购买
            if(goods.getShopType().equals(ShopTypeConstant.MC_SC)){
                MyPasture myPasture =myPastureRepository.findByOpenId(receiveMsg.getFromUserName());
                if (myPasture==null){
                    replyContent="购买失败，未购买牧场，请购买牧场后再购买相关物品";
                    return replyContent;
                }
                if (goods.getGoodsLevel()>myPasture.getLevel()){
                    replyContent ="购买失败,当前牧场等级不足";
                    return replyContent;
                }
            }
            //判断物品类型。非卖品无法购买
            if (goods.getShopType()==ShopTypeConstant.SC_FM){
                replyContent="购买失败，当前物品为非卖品！";
            }else {
                User user = userRepository.findByOpenId(receiveMsg.getFromUserName());
                if (goods.getCurrency()== CurrencyEnum.JB.getType()){
                    Integer userJB = user.getJinbi();
                    Integer useJB=Integer.valueOf(goodsNum)*goods.getPrice();
                    if (userJB>=useJB){
                        //更新下用户的金币
                        user.setJinbi(userJB-useJB);
                        mongoTemplate.save(user);
                        //添加物品到背包
                        //判断物品是否存在，存在则修改数量，不存在则添加
                        MyBag myBag = myBagRepository.findByGoodsNameAndOpenId(goodsName,receiveMsg.getFromUserName());
                        if (myBag!=null){
                            myBag.setNum(myBag.getNum()+Integer.valueOf(goodsNum));
                        }else {
                            myBag=new MyBag();
                            myBag.setNum(Integer.valueOf(goodsNum));
                            myBag.setGoodsName(goodsName);
                            myBag.setOpenId(receiveMsg.getFromUserName());
                            myBag.setType(goods.getShopType());
                        }
                        mongoTemplate.save(myBag);
                        //商城物品购买
                        if (goods.getShopType().equals(ShopTypeConstant.MC_SC)){
                            PastureGoodsInfo goodsInfo = pastureGoodsInfoRepository.findByGoodsName(goodsName);
                            replyContent="✅恭喜您购买成功，获得"+goodsNum+"个"+goodsName+",共花费"+useJB+"💰金币,已放入您的【<a href=\"weixin://bizmsgmenu?msgmenuid=1&msgmenucontent=牧场背包\">牧场背包</a>】";
                        }else {
                            replyContent="✅恭喜您购买成功，获得"+goodsNum+"个"+goodsName+",共花费"+useJB+"💰金币,已放入您的背包";
                        }
                    }else {
                        replyContent="购买失败，金币不足！";
                    }
                }else if (goods.getCurrency()== CurrencyEnum.ZS.getType()){
                    //todo 钻石消耗
                }else {
                    replyContent="购买失败，物品货币异常！";
                }
            }
        }else {
            replyContent="购买失败，物品不存在！";
        }
        return replyContent;
    }


    /** 
    * @Description: 查看详情
     * @param replyContent
 * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/18 20:32
    */
    
    private String lookInfo(String replyContent, ReceiveMsg receiveMsg) {
        String content = receiveMsg.getContent();
        String goodsName = content.split("#")[1];
        ShopGoods goods =shopGoodsRepository.findByGoodsName(goodsName);
        if (goods!=null){
            //查看牧场物品属性
            if (goods.getShopType().equals(ShopTypeConstant.MC_SC)){

                StringBuffer buffer = new StringBuffer();
                PastureGoodsInfo goodsInfo =pastureGoodsInfoRepository.findByGoodsName(goodsName);
                Integer czTime=goodsInfo.getCubStageTime()+goodsInfo.getGrowthPeriodTime();
                buffer.append("成长时间:"+czTime+"小时\n");
                buffer.append("生产时间:"+goodsInfo.getProduceTotalTime()+"小时\n");
                buffer.append("预计产量:"+goodsInfo.getYieldNum()+"\n");
                buffer.append("产物价值:"+goodsInfo.getCubPrice()+"金币\n");
                buffer.append("动物价值:"+goodsInfo.getSellingRate()+"金币\n");
                buffer.append("领养等级:"+goodsInfo.getLevel()+"\n");
                String jz="";
                if (goodsInfo.getHabitationType()==1){ jz="窝"; }else {  jz="棚"; }
                buffer.append("居住地:"+jz);
                replyContent=  replyContent.replace("{goodsName}",goods.getGoodsName()).replace("{price}",goods.getPrice().toString()+"金币")
                        .replace("{remark}",buffer.toString());
            }else {
                replyContent=  replyContent.replace("{goodsName}",goods.getGoodsName()).replace("{price}",goods.getPrice().toString())
                        .replace("{remark}",goods.getRemark());
            }

        }else {
            replyContent="物品不存在";
        }
        return replyContent;
    }

    /** 
    * @Description: 金币商城
    * @params:  * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/3/28 20:09
    */
    private String JBShopReply(String replyContent, ReceiveMsg receiveMsg) {
        //查询物品
        List<ShopGoods> shopGoods = new ArrayList<>();
        shopGoods = shopGoodsRepository.findAllByShopType(ShopTypeConstant.JB_SC);
        int i = 0;
        for (ShopGoods goods:shopGoods){
            i=i+1;
            replyContent=replyContent.replace("{"+i+"}",goods.getGoodsName());
        }

        return replyContent;
    }



    
    /** 
    * @Description: 通过stringbuffer替换
    * @params:  * @param i
    * @param replyContent
    * @param shopGoods
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/3/28 20:27
    */
    public String StrBufferChange(int i,String replyContent,List<ShopGoods>  shopGoods){
        StringBuffer stringBuffer = new StringBuffer();
        for (ShopGoods goods:shopGoods){
            i=i+1;
            if (i>2){
                i=1;
            }
            if (i == 1) {
                stringBuffer.append(goods.getGoodsName()+"|");
            }
            if (i==2){
                stringBuffer.append(goods.getGoodsName()+"\n");
            }
        }
        replyContent=stringBuffer.toString();
        return replyContent;
    }
}
